import GeoJSON from 'ol/format/GeoJSON.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import { Fill, Stroke, Style, Text, Icon } from 'ol/style';
import { Vector as VectorSource } from 'ol/source.js';
import { Vector as VectorLayer, Image } from 'ol/layer';
import { click, platformModifierKeyOnly } from 'ol/events/condition';
import { Select, DragPan, MouseWheelZoom } from 'ol/interaction';
import { defaults as defaultControls } from 'ol/control';
import { addCityImage, addAreaImage } from './addImage';
import { createTransform } from './createTransform';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Overlay from 'ol/Overlay';

import * as echarts from 'echarts';

import { platformList } from '@/api/serve';

const features = new GeoJSON({ featureProjection: 'EPSG:4326' });
const featuresArea = new GeoJSON({ featureProjection: 'EPSG:4326' });
// 宁波市json
export const vectorSource = new VectorSource({ format: features, url: 'json/330200.json' });
// 宁波市区县json
export const vectorSourceArea = new VectorSource({ format: featuresArea, url: 'json/330200_full.json' });

// 宁波市
export function createCity() {
    const getStyle = (feature) => {
        return new Style({
            stroke: new Stroke({
                color: 'rgb(191,255,255)',
                width: 4
            }),
            fill: new Fill({
                color: 'rgba(77,94,131,0)'
            })
        });
    };

    return new VectorLayer({
        source: vectorSource,
        zIndex: 4,
        style: getStyle
    });
}

// 宁波区县
export function createArea(style) {
    const getStyle = style || ((feature) => {
        return new Style({
            stroke: new Stroke({
                color: 'rgba(255,255,255,0.7)',
                width: 1
            }),
            fill: new Fill({
                color: 'rgba(0,0,0,0)'
            }),
            text: new Text({
                text: feature.get('name'),
                overflow: false,
                fill: new Fill({ color: '#fff' }),
                font: 'normal normal 24px MicrosoftYaHei'
            })
        });
    });

    return new VectorLayer({
        source: vectorSourceArea,
        zIndex: 10,
        style: getStyle
    });
}

export function createMap() {
    return new Map({
        target: 'ol-map',
        view: new View({
            projection: 'EPSG:4326',
            center: [121.5, 29.52],
            zoom: 9.7,
            minZoom: 9.7,
            maxZoom: 9.7
        }),
        // 隐藏放大放小按钮
        controls: defaultControls({
            zoom: false,
            rotate: false,
            attribution: false
        })
    });
}

// 点击事件
export function createSelect(layers, imageAreaMap) {
    // 区县图片图层
    console.log(imageAreaMap, 'imageAreaMap');
    let lastAreaName = null;
    const selectStyle = (feature) => {
        const adcode = feature.get('adcode');
        lastAreaName && imageAreaMap[lastAreaName] && imageAreaMap[lastAreaName].setVisible(false);
        imageAreaMap[adcode] && imageAreaMap[adcode].setVisible(true);
        lastAreaName = adcode;

        return new Style({
            zIndex: 100,
            stroke: new Stroke({
                color: 'rgba(0,0,0,0)',
                // color: 'red',
                width: 5
            }),
            fill: new Fill({
                color: 'rgba(77,94,131,0)'
            }),
            text: new Text({
                text: feature.get('name'),
                overflow: false,
                fill: new Fill({ color: '#fff' }),
                font: 'normal normal 24px MicrosoftYaHei'
            })
        });
    };
    return new Select({
        condition: click,
        layers: [layers],
        toggleCondition: platformModifierKeyOnly,
        style: selectStyle
    });
}

export function createTransformLayer(amap, imageAreaMap) {
    const layerArea = createArea((feature) => {
        return new Style({
            zIndex: 20,
            stroke: new Stroke({
                color: 'rgba(77,94,131,0)',
                width: 1
            }),
            fill: new Fill({
                color: 'rgba(77,94,131,0)'
            }),
            text: new Text({
                text: feature.get('name'),
                overflow: false,
                fill: new Fill({ color: '#fff' }),
                font: 'normal normal 24px MicrosoftYaHei'
            })
        });
    });
    amap.addLayer(layerArea);
    createTransform(amap, layerArea, imageAreaMap);
}
const addAreaImagePoint = (map) => {
    const tempPoints = [];
    const locList = [{
            geometry: new Point([121.29469449617675 + 0.18, 29.749373483649762 - 0.37]),
            name: '宁海县',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.54, 29.749373483649762 - 0.32]),
            name: '象山县',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.15, 29.749373483649762 - 0.08]),
            name: '奉化区',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.35, 29.749373483649762 + 0.09]),
            name: '鄞州区',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.62, 29.749373483649762 + 0.17]),
            name: '北仑区',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.37, 29.749373483649762 + 0.3]),
            name: '镇海区',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.15, 29.749373483649762 + 0.28]),
            name: '江北区',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 - 0.08, 29.749373483649762 + 0.33]),
            name: '余姚市',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675, 29.749373483649762 + 0.58]),
            name: '慈溪市',
            type: 'city'
        },
        {
            geometry: new Point([121.29469449617675 + 0.08, 29.749373483649762 + 0.15]),
            name: '海曙区',
            type: 'city'
        }

    ];
    locList.forEach(item => {
        const feature = new Feature({
            geometry: item.geometry,
            self: item
        });
        const iconStyle = new Style({
            image: new Icon({
                src: require('./img/areaLoc.png'),
                scale: 1,
                opacity: 1
            })
        });
        feature.setStyle(iconStyle);
        tempPoints.push(feature);
    });
    const vectorSource = new VectorSource({
        features: tempPoints
    });
    const vectorLayer = new VectorLayer({
        zIndex: 150,
        source: vectorSource
    });
    map.addLayer(vectorLayer);

    return tempPoints;
};
let overlayForm;
let areaImagePointList;
let imageAreaMap;
let interactionSelectArea;
let mapData = [];
let layerCity;
let isClickButton = false;
let timer = null;
let index = 0;
let isMouseenter = false;
const areaList = [{
        loc: [121.29469449617675 + 0.45, 29.749373483649762 + 0.22],
        loc2: [121.29469449617675 + 0.55, 29.749373483649762 + 0.2],
        name: '市本级',
        code: '330200',
        l: 'l2',
        c: 'sbj'
    },
    {
        loc: [121.29469449617675 + 0.18, 29.749373483649762 - 0.37],
        loc2: [121.29469449617675 - 1.1, 29.749373483649762],
        name: '宁海县',
        code: '330226',
        l: 'l3',
        c: 'nh'
    },
    {
        loc: [121.29469449617675 + 0.54, 29.749373483649762 - 0.32],
        loc2: [121.29469449617675 + 0.55, 29.749373483649762 + 0.0],
        name: '象山县',
        code: '330225',
        l: 'l6',
        c: 'xs'
    },
    {
        loc: [121.29469449617675 + 0.15, 29.749373483649762 - 0.08],
        loc2: [121.29469449617675 - 1.1, 29.749373483649762 + 0.2],
        name: '奉化区',
        code: '330213',
        l: 'l3',
        c: 'fh'
    },
    {
        loc: [121.29469449617675 + 0.35, 29.749373483649762 + 0.09],
        loc2: [121.29469449617675 + 0.51, 29.749373483649762 + 0.4],
        name: '鄞州区',
        code: '330212',
        l: 'l',
        c: 'yz'
    },
    {
        loc: [121.29469449617675 + 0.62, 29.749373483649762 + 0.17],
        loc2: [121.29469449617675 + 0.54, 29.749373483649762 + 0.3],
        name: '北仑区',
        code: '330206',
        l: 'l5',
        c: 'bl'
    },
    {
        loc: [121.29469449617675 + 0.37, 29.749373483649762 + 0.3],
        loc2: [121.29469449617675 + 0.55, 29.749373483649762 + 0.48],
        name: '镇海区',
        code: '330211',
        l: 'l7',
        c: 'zh'
    },
    {
        loc: [121.29469449617675 + 0.15, 29.749373483649762 + 0.28],
        loc2: [121.29469449617675 + 0.3, 29.749373483649762 + 0.4],
        name: '江北区',
        code: '330205',
        l: 'l6',
        c: 'jb'
    },
    {
        loc: [121.29469449617675 - 0.08, 29.749373483649762 + 0.33],
        loc2: [121.29469449617675 - 1.15, 29.749373483649762 + 0.3],
        name: '余姚市',
        code: '330281',
        l: 'l4',
        c: 'yy'
    },
    {
        loc: [121.29469449617675, 29.749373483649762 + 0.58],
        loc2: [121.29469449617675 + 0.1, 29.749373483649762 + 0.48],
        name: '慈溪市',
        code: '330282',
        l: 'l2',
        c: 'cx'
    },
    {
        loc: [121.29469449617675 + 0.08, 29.749373483649762 + 0.15],
        loc2: [121.29469449617675 - 1.1, 29.749373483649762 + 0.45],
        name: '海曙区',
        code: '330203',
        l: 'l3',
        c: 'hs'
    }

];
const addPopupModal = (amap) => {
    overlayForm = new Overlay({
        // 创建一个图层
        autoPan: true,
        positioning: 'center-left',
        // offset: [-10, -20],
        offset: [0, 15],
        autoPanAnimation: {
            duration: 250
        }
    });
    overlayForm.setPosition(undefined);
    amap.addOverlay(overlayForm);
};
const clear = () => {
    overlayForm.setPosition(undefined);
    areaImagePointList.forEach(feature => {
        const iconStyle = new Style({
            image: new Icon({
                src: require('./img/areaLoc.png'),
                scale: 1,
                opacity: 1
            })
        });
        feature.setStyle(iconStyle);
    });
    Object.keys(imageAreaMap).forEach(key => {
        imageAreaMap[key].setVisible(false);
    });

    const style = new Style({
        stroke: new Stroke({
            color: 'rgb(191,255,255)',
            width: 4
        })
    });
    layerCity.setStyle(style);
    isClickButton = false;
};
let doc1, doc2, doc3, doc4;
const openPopupModal = (name, code) => {
    doc1 = null;
    doc2 = null;
    doc3 = null;
    doc4 = null;
    console.log('openPopupModal');
    const getCode = areaList.find(item => item.name === name);
    let getData = {};

    getData = mapData.find(item => {
        if (item.platformId === getCode.code || code) {
            return item;
        }
    });
    const ele = areaList.find((item) => {
        return item.name === name;
    });
    if (!getData) getData = {};
    let a1;
    let b1;
    let c1;
    let d1;
    let e1;
    const d111 = getData.appealCountScreenConfig;
    if (getData.appealCountScreenConfig) {
        a1 = d111.handledResultCount;
        b1 = d111.processingResultCount;
        c1 = d111.handleTimeResultGapAvg;
        d1 = d111.overdueResultCount;
        e1 = d111.totalResultCount;
    }
    let html = `
    <div class="mapm" >
        <div class="mapModal" id="myMapModal">
            <div class="title">${name}</div>
            <div class="message">
                <div class="item">
                    <div class="num">${a1 || 0}</div>
                    <div class="text">已办结<br/>(件)</div>
                </div>
                <div class="item">
                    <div class="num">${b1 || 0}</div>
                    <div class="text">处理中<br/>(件)</div>
                </div>
                <div class="item">
                    <div class="num">${c1 || 0}</div>
                    <div class="text">平均办结天数<br/>(天)</div>
                </div>
                <div class="item">
                    <div class="num">${d1 || 0}</div>
                    <div class="text">超时未办结<br/>(件)</div>
                </div>
            </div>
            <div class="bar">
                <div class="b1">
                    <div id="mapEcharts2"></div>
                    <div class="num2">${getData.handledCountPresent || 0}<span>%</span></div>
                    <div class="title2">办结率</div>
                </div>
                <div class="b2"></div>
                <div class="b1">
                    <div id="mapEcharts"></div>
                    <div class="num2">${getData.satisfactionPresent || 0}<span>%</span></div>
                    <div class="title2">企业满意率</div>
                </div>
            </div>
            <div class="table">
                <div class="thead">
                    <div class="th1">板块</div>
                    <div class="th2">问题总数</div>
                    <div class="th3">已办结</div>
                    <div class="th4">处理中</div>
                    <div class="leftBottomIcon"></div>
                </div>
                <div class="otherList">
                
    `;
    if (getData.appealMainClassCountMapList) {
        for (let i = 0; i < getData.appealMainClassCountMapList.length; i++) {
            const dd = getData.appealMainClassCountMapList[i];
            html +=
                `<div class="list">
                    <div class="line">
                        <div class="th1">${dd.name}</div>
                        <div class="th2">${dd.totalResultCount}</div>
                        <div class="th3">${dd.handledResultCount}</div>
                        <div class="th4">${dd.processingResultCount}</div>
                    </div>
                </div>`;
        }
    }

    const htmlEnd = `
                </div>
            </div>
        </div>
        <div class="${ele.l}"></div>
        <div class="mapClose" id="mapClose"></div>
        <div class="mapbgMessage ${ele.c}">
            <div>问题数：${e1 || 0}</div>
            <div>评价指数：${getData.satisfactionPresent || 0}</div>
        </div>
    </div>
    `;
    html += htmlEnd;
    const parser = new DOMParser();
    const eleDom = parser.parseFromString(html, 'text/html').body
        .childNodes[0];
    overlayForm.setElement(eleDom);

    overlayForm.setPosition([ele.loc2[0] + 0.09, ele.loc2[1] - 0.2]);
    doc1 = document.getElementById('mapClose');
    if (doc1) {
        doc1.addEventListener('click', () => {
            // 清空选项
            interactionSelectArea.getFeatures().clear();
            clear();
        });
    }
    doc2 = document.getElementById('myMapModal');
    if (doc2) {
        doc2.addEventListener('mouseenter', function() {
            isMouseenter = true;
            console.log('移入地图');
        });
        doc2.addEventListener('mouseleave', function() {
            isMouseenter = false;
            console.log('移出地图');
        });
    }

    // setTimeout(() => {
    // if (isFirst) {
    doc3 = document.getElementById('mapEcharts');
    var myChart = echarts.init(doc3);
    const option = {
        series: [{
            type: 'gauge', // 类型：仪表盘图
            name: '制造业',
            center: ['50%', '50%'], // 仪表盘图的中心点相对于dom容器的位置
            radius: '74%', // 环形的大小
            axisLine: {
                show: true,
                lineStyle: {
                    color: [
                        [(getData.satisfactionPresent / 100).toFixed(1), {
                            type: 'linear',
                            x: 1,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                    offset: 1,
                                    color: 'rgba(80,209,255,0)' // 0% 处的颜色
                                },
                                {
                                    offset: 0,
                                    color: '#50FFE2' // 100% 处的颜色
                                }
                            ],
                            global: false // 缺省为 false
                        }],
                        [1, '#082568']
                    ],
                    width: 18 // 环形的粗细
                }
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                show: false
            },
            pointer: {
                show: false
            }
        }]
    };
    option && myChart.setOption(option);

    doc4 = document.getElementById('mapEcharts2');
    var myChart2 = echarts.init(doc4);
    const option2 = {
        series: [{
            type: 'gauge', // 类型：仪表盘图
            name: '制造业',
            center: ['50%', '50%'], // 仪表盘图的中心点相对于dom容器的位置
            radius: '74%', // 环形的大小
            axisLine: {
                show: true,
                lineStyle: {
                    color: [
                        [(getData.handledCountPresent / 100).toFixed(1), {
                            type: 'linear',
                            x: 1,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                    offset: 1,
                                    color: 'rgba(80,209,255,0)' // 0% 处的颜色
                                },
                                {
                                    offset: 0,
                                    color: '#50FFE2' // 100% 处的颜色
                                }
                            ],
                            global: false // 缺省为 false
                        }],
                        [1, '#082568']
                    ],
                    width: 18 // 环形的粗细
                }
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                show: false
            },
            pointer: {
                show: false
                    // width: 40,
                    // showAbove: true,
                    // itemStyle: {
                    //     color: 'red'
                    // },
                    // offsetCenter: [0, 0]
            }
        }]
    };
    option2 && myChart2.setOption(option2);
    // }

    // }, 3000);
};

export function clickBtn() {
    if (isClickButton) return;
    isClickButton = true;
    interactionSelectArea.getFeatures().clear();
    clear();
    const style = new Style({
        stroke: new Stroke({
            color: 'rgba(255, 243, 0, 1)',
            width: 4
        })
    });
    layerCity.setStyle(style);
    console.log('clickBtn-map');
    openPopupModal('市本级', '330200');
}
const getPan = (amap) => {
    let pan = null;
    amap.getInteractions().forEach((element) => {
        if (element instanceof DragPan) {
            pan = element;
        }
    });
    return pan;
};
const setTimeSelect = () => {
    timer = setInterval(() => {
        // if (index > vectorSourceArea.getFeatures().length) {
        //     index = 0;
        // }
        console.log(isMouseenter, 'isMouseenter');
        if (isMouseenter) {
            return;
        }
        const feature2 = vectorSourceArea.getFeatures()[index];
        if (feature2) {
            interactionSelectArea.getFeatures().clear();
            interactionSelectArea.getFeatures().push(feature2);
            clickArea();
        } else {
            index = -1;
            clickBtn();
        }
        index++;
    }, 10000);
};

// 点击区块触发事件
const clickArea = () => {
    // 状态清空
    clear();
    // 开始渲染
    if (interactionSelectArea.getFeatures().getArray().length > 0) {
        const name = interactionSelectArea.getFeatures().getArray()[0].values_.name;
        const feature = areaImagePointList.find(feature => {
            return feature.values_.self.name === name;
        });
        const iconStyle = new Style({
            image: new Icon({
                src: require('./img/areaLoc2.png'),
                scale: 1,
                opacity: 1
            })
        });
        feature.setStyle(iconStyle);
        // 打开弹窗
        console.log('clickArea-map');
        openPopupModal(name);
    }
};
export function init() {
    const amap = createMap();
    layerCity = createCity();
    const layerArea = createArea();

    amap.addLayer(layerArea);

    // 宁波市底图
    addCityImage(amap, layerCity);
    // 区县底图
    imageAreaMap = addAreaImage(amap);
    setTimeout(() => {
        amap.addLayer(layerCity);
        // 区县点位
        areaImagePointList = addAreaImagePoint(amap);
    }, 500);

    // 选中后样式
    interactionSelectArea = createSelect(layerArea, imageAreaMap);
    // 区块点击
    interactionSelectArea.on('select', e => {
        if (interactionSelectArea.getFeatures().getArray().length > 0) {
            clearInterval(timer);
            setTimeSelect();
        }
        clickArea();
    });
    amap.addInteraction(interactionSelectArea);

    // 弹窗
    addPopupModal(amap);

    // 拿图片imageExtent范围用的 图片位置调完注释掉
    // createTransformLayer(amap, imageAreaMap);

    // 获取数据
    platformList().then(res => {
        mapData = res.data.result;
        // 第一次默认选中
        setTimeout(() => {
            // const feature2 = vectorSourceArea.getFeatures()[0];
            // interactionSelectArea.getFeatures().push(feature2);
            // clickArea();
            clickBtn();
        }, 500);
    });

    // 阻止拖拽
    const pan = getPan(amap);
    pan.setActive(false);

    // 循环轮播选中
    setTimeSelect();

    const overlayForm2 = new Overlay({
        autoPan: true,
        positioning: 'center-left',
        offset: [0, 15],
        autoPanAnimation: {
            duration: 250
        }
    });
    overlayForm2.setPosition(undefined);
    amap.addOverlay(overlayForm2);
    const html = `<div class="myButton2" id="myButton2">切换至市本级</div>`;
    const parser = new DOMParser();
    const eleDom = parser.parseFromString(html, 'text/html').body
        .childNodes[0];
    overlayForm2.setElement(eleDom);
    overlayForm2.setPosition([121.29469449617675 + 1.07, 29.749373483649762 + 0.73]);
    document.getElementById('myButton2').addEventListener('click', () => {
        // 清空选项
        clickBtn();
    });

    // 鼠标离开地图启动定时器

    // 鼠标进入地图关闭定时器
    // areaImagePointList.forEach(point => {
    //     point.on('pointermove', () => {
    //         alert(1);
    //     });
    // });
    return amap;
}
